package com.wenjiang.service.impl;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.request.AlipayUserInfoShareRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayUserInfoShareResponse;
import com.wenjiang.entity.AliPayUser;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@Service
@ConfigurationProperties(prefix = "alilogin")
@Data
@Slf4j
public class AiliLoginServiceImpl implements InitializingBean {

    private String appId;

    private String gatewayUrl;

    private String publicKey;

    private String privateKey;

    private String callbackUrl;


    private String scope="auth_user";





    /**Alipay客户端*/
    private AlipayClient alipayClient;

    //配置专填后的方法
    @Override
    public void afterPropertiesSet() throws Exception {
         //装填当前的数据
        alipayClient = new DefaultAlipayClient(gatewayUrl, appId, privateKey, "json", "UTF-8", publicKey,
                "RSA2");
    }


    /**
     * 根据auth_code获取用户的user_id和access_token
     * @param authCode
     * @return
     */
    public String getAccessToken(String authCode) {
        AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
        request.setCode(authCode);
        request.setGrantType("authorization_code");
        try {
            AlipaySystemOauthTokenResponse oauthTokenResponse = alipayClient.execute(request);
            return oauthTokenResponse.getAccessToken();
        } catch (Exception e) {
            log.error("使用authCode获取信息失败！", e);
            return null;
        }
    }

    /**
     * 根据access_token获取用户信息
     * @param token
     * @return
     */
    public AliPayUser getUserInfoByToken(String token) {
        AlipayUserInfoShareRequest request = new AlipayUserInfoShareRequest ();
        try {
            AlipayUserInfoShareResponse response =  alipayClient.execute(request, token);
            if (response.isSuccess()) {
                //打印响应信息
//                System.out.println(ReflectionToStringBuilder.toString(response));
                //封装支付宝对象信息
                AliPayUser alipayUser = new AliPayUser();
                alipayUser.setAddress(response.getAddress());
                //获取用户头像
                alipayUser.setUserImgUrl(response.getAvatar());
                //获取支付宝用户名
                alipayUser.setUsername(response.getUserName());

                //获取支付宝的用户id
                alipayUser.setAliPayId(response.getUserId());



                response.getCertNo();

//                alipayUser.setCertNo(response.getCertNo());
//                alipayUser.setCity(response.getCity());
//                alipayUser.setCollegeName(response.getCollegeName());
//                alipayUser.setDegree(response.getDegree());
//                alipayUser.setMobile(response.getMobile());
//                alipayUser.setPhone(response.getPhone());
//                alipayUser.setProvince(response.getProvince());
//                alipayUser.setUserName(response.getUserName());
//                alipayUser.setNickName(response.getNickName());
                return alipayUser;
            }
            log.error("根据 access_token获取用户信息失败!");
            return null;

        } catch (Exception e) {
            log.error("根据 access_token获取用户信息抛出异常！", e);
            return null;
        }
    }


    //生成访问的url

    public  String createUrl() throws UnsupportedEncodingException {
        StringBuffer stringBuffer= new StringBuffer();
       stringBuffer.append("https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id="+appId)
               .append("&scope="+scope)//接口权限值，目前只支持auth_user和auth_base两个值
               .append("&redirect_uri="+ URLEncoder.encode(callbackUrl,"utf-8"));

       return stringBuffer.toString();
    }
}
